<?php
/**
 * 3-4岁专区认知内容编辑页面
 */
require_once '../../../admin/check_session.php';
require_once '../../../includes/config.php';
require_once '../includes/CognitiveManager34.php';
require_once '../../../includes/MediaManager.php';

// 创建认知管理器实例
$cognitiveManager = new CognitiveManager34();
$mediaManager = new MediaManager();

// 检查模块ID参数
if (!isset($_GET['module_id'])) {
    // 如果没有提供模块ID，重定向到模块列表页面
    header("Location: cognitive_modules.php");
    exit;
}

$moduleId = (int)$_GET['module_id'];
$module = $cognitiveManager->getModuleById($moduleId);

// 验证模块存在且属于3-4岁年龄段
if (!$module) {
    // 如果模块不存在或不属于3-4岁年龄段，重定向到模块列表页面
    header("Location: cognitive_modules.php?error=invalid_module");
    exit;
}

// 初始化内容数据
$content = [
    'content_id' => 0,
    'module_id' => $moduleId,
    'content_title' => '',
    'content_key' => '',
    'description' => '',
    'content_order' => 0,
    'color_code' => '',
    'title_audio_id' => null,
    'is_active' => 1
];

// 检查是否是编辑现有内容
$isEditing = false;
if (isset($_GET['id'])) {
    $contentId = (int)$_GET['id'];
    $existingContent = $cognitiveManager->moduleManager->getContentById($contentId);
    
    if ($existingContent && $existingContent['module_id'] == $moduleId) {
        $content = $existingContent;
        $isEditing = true;
    }
}

// 获取已上传的标题音频文件（如果有）
$titleAudio = null;
if (!empty($content['title_audio_id'])) {
    $titleAudio = $mediaManager->getMediaById($content['title_audio_id']);
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 收集表单数据
    $contentData = [
        'module_id' => $moduleId,
        'content_title' => $_POST['content_title'],
        'content_key' => $_POST['content_key'],
        'description' => $_POST['description'],
        'content_order' => (int)$_POST['content_order'],
        'color_code' => $_POST['color_code'],
        'is_active' => isset($_POST['is_active']) ? 1 : 0
    ];
    
    // 处理标题音频上传
    if (isset($_FILES['title_audio']) && $_FILES['title_audio']['error'] === UPLOAD_ERR_OK) {
        $audioFile = $_FILES['title_audio'];
        $uploadResult = $mediaManager->uploadMedia($audioFile, 'audio', "cognitive/contents/{$moduleId}");
        
        if ($uploadResult && isset($uploadResult['media_id'])) {
            $contentData['title_audio_id'] = $uploadResult['media_id'];
        } else {
            $errorMessage = "上传音频文件时出错";
        }
    } else if (isset($_POST['remove_audio']) && $_POST['remove_audio'] == 1) {
        $contentData['title_audio_id'] = null;
    } else if (!empty($content['title_audio_id'])) {
        $contentData['title_audio_id'] = $content['title_audio_id'];
    }
    
    // 验证必填字段
    $errors = [];
    if (empty($contentData['content_title'])) {
        $errors[] = "内容标题不能为空";
    }
    
    if (empty($contentData['content_key'])) {
        $errors[] = "内容Key不能为空";
    } else {
        // 检查content_key格式（只允许字母、数字和下划线）
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $contentData['content_key'])) {
            $errors[] = "内容Key只能包含字母、数字和下划线";
        }
        
        // 检查重复的content_key
        if (!$isEditing || $contentData['content_key'] !== $content['content_key']) {
            $sql = "SELECT content_id FROM cognitive_contents 
                    WHERE content_key = ? AND module_id = ? AND content_id != ?";
            $existingContent = $cognitiveManager->db->fetchRow($sql, [
                $contentData['content_key'], 
                $moduleId,
                $isEditing ? $content['content_id'] : 0
            ]);
            
            if ($existingContent) {
                $errors[] = "内容Key已存在，请使用其他标识符";
            }
        }
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        if ($isEditing) {
            // 更新现有内容
            $result = $cognitiveManager->moduleManager->updateContent($contentId, $contentData);
            
            if ($result) {
                $successMessage = "内容已成功更新";
                // 重新加载内容数据
                $content = $cognitiveManager->moduleManager->getContentById($contentId);
                if (!empty($content['title_audio_id'])) {
                    $titleAudio = $mediaManager->getMediaById($content['title_audio_id']);
                } else {
                    $titleAudio = null;
                }
            } else {
                $errorMessage = "更新内容时出错";
            }
        } else {
            // 添加新内容
            $newContentId = $cognitiveManager->moduleManager->addContent($contentData);
            
            if ($newContentId) {
                // 重定向到内容列表页面
                header("Location: cognitive_contents.php?module_id={$moduleId}&success=1");
                exit;
            } else {
                $errorMessage = "添加内容时出错";
            }
        }
    }
}

// 添加页面标题
$pageTitle = $isEditing ? "编辑 "{$content['content_title']}"" : "添加新内容";
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - KidsMind管理后台</title>
    <!-- 引入管理后台通用样式 -->
    <link rel="stylesheet" href="/admin/css/admin.css">
    <link rel="stylesheet" href="/admin/css/bootstrap.min.css">
    <link rel="stylesheet" href="/admin/css/fontawesome.min.css">
    <!-- 颜色选择器 -->
    <link rel="stylesheet" href="/admin/css/spectrum.min.css">
    <!-- 3-4岁专用样式 -->
    <style>
        .form-card {
            border-radius: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            background-color: #fff;
            padding: 30px;
            margin-bottom: 30px;
        }
        .preview-card {
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            background-color: <?php echo getColorCode($module['background_color']); ?>;
        }
        .preview-title {
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .color-preview {
            width: 40px;
            height: 40px;
            display: inline-block;
            border-radius: 50%;
            margin-right: 10px;
            border: 2px solid #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .audio-preview {
            margin-top: 15px;
            padding: 10px;
            background-color: rgba(255,255,255,0.5);
            border-radius: 10px;
        }
        .audio-preview audio {
            width: 100%;
            border-radius: 8px;
        }
        .audio-upload-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        .audio-upload-wrapper input[type=file] {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        .module-link {
            text-decoration: none;
            color: inherit;
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .module-link:hover {
            color: #0d6efd;
        }
        .module-icon {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        /* 马卡龙色系配色 */
        .bg-pastel-pink { background-color: #FFD6E0; }
        .bg-pastel-blue { background-color: #D6E5FF; }
        .bg-pastel-green { background-color: #D6FFE1; }
        .bg-pastel-yellow { background-color: #FFEFD6; }
        .bg-pastel-purple { background-color: #E9D6FF; }
    </style>
</head>
<body>
    <?php include '../../../admin/includes/header.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include '../../../admin/includes/sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2"><?php echo $pageTitle; ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>" class="btn btn-sm btn-outline-secondary">返回内容列表</a>
                        </div>
                    </div>
                </div>
                
                <?php if (isset($successMessage)): ?>
                <div class="alert alert-success" role="alert">
                    <?php echo $successMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($errorMessage)): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo $errorMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger" role="alert">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <!-- 显示所属模块 -->
                <a href="cognitive_modules.php" class="module-link">
                    <span class="module-icon"><?php echo $module['icon']; ?></span>
                    <span><?php echo htmlspecialchars($module['module_name']); ?></span>
                </a>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-card">
                            <form method="post" action="" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="content_title" class="form-label">内容标题 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="content_title" name="content_title" 
                                           value="<?php echo htmlspecialchars($content['content_title']); ?>" required>
                                    <div class="form-text">例如："红色"、"圆形"等</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="content_key" class="form-label">内容Key <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="content_key" name="content_key" 
                                           value="<?php echo htmlspecialchars($content['content_key']); ?>" required>
                                    <div class="form-text">用于URL和标识的简短关键字，如"red"、"circle"（只能包含字母、数字和下划线）</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label">内容描述</label>
                                    <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($content['description']); ?></textarea>
                                    <div class="form-text">简洁描述该内容，适合3-4岁儿童理解</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="color_code" class="form-label">颜色代码</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="color_code" name="color_code" 
                                               value="<?php echo htmlspecialchars($content['color_code']); ?>">
                                        <button class="btn btn-outline-secondary" type="button" id="pick-color">选择</button>
                                    </div>
                                    <div class="form-text">为内容选择一个代表色（如有颜色相关内容）</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="content_order" class="form-label">显示顺序</label>
                                    <input type="number" class="form-control" id="content_order" name="content_order" 
                                           value="<?php echo (int)$content['content_order']; ?>" min="0">
                                    <div class="form-text">数字越小，显示越靠前</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">标题音频</label>
                                    <?php if ($titleAudio): ?>
                                    <div class="mb-2">
                                        <div class="d-flex align-items-center">
                                            <audio controls src="<?php echo $titleAudio['file_path']; ?>"></audio>
                                            <div class="form-check ms-3">
                                                <input class="form-check-input" type="checkbox" id="remove_audio" name="remove_audio" value="1">
                                                <label class="form-check-label" for="remove_audio">移除音频</label>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="audio-upload-wrapper">
                                        <button class="btn btn-outline-primary" type="button"><?php echo $titleAudio ? '替换音频' : '上传音频'; ?></button>
                                        <input type="file" name="title_audio" accept="audio/*">
                                    </div>
                                    <div class="form-text">上传朗读标题的音频，帮助孩子学习发音</div>
                                </div>
                                
                                <div class="mb-4 form-check">
                                    <input type="checkbox" class="form-check-input" id="is_active" name="is_active" 
                                           <?php echo $content['is_active'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">激活内容</label>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>" class="btn btn-outline-secondary me-md-2">取消</a>
                                    <button type="submit" class="btn btn-primary">保存内容</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="sticky-top" style="top: 80px;">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">内容预览</h5>
                                </div>
                                <div class="card-body">
                                    <div class="preview-card">
                                        <div class="preview-title">
                                            <div id="preview-color" class="color-preview" 
                                                 style="background-color: <?php echo !empty($content['color_code']) ? $content['color_code'] : 'transparent'; ?>"></div>
                                            <span id="preview-title"><?php echo htmlspecialchars($content['content_title'] ?: '内容标题'); ?></span>
                                        </div>
                                        <p id="preview-description" class="text-muted">
                                            <?php echo nl2br(htmlspecialchars($content['description'] ?: '内容描述将显示在这里...')); ?>
                                        </p>
                                        <?php if ($titleAudio): ?>
                                        <div class="audio-preview">
                                            <small class="d-block mb-1 text-muted">标题音频:</small>
                                            <audio controls src="<?php echo $titleAudio['file_path']; ?>"></audio>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">提示</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="mb-0">
                                        <li>内容标题应简洁明了，适合3-4岁儿童</li>
                                        <li>若内容与颜色相关，请选择对应的颜色代码</li>
                                        <li>添加音频可以帮助孩子学习正确的发音</li>
                                        <li>保存后，可以为内容添加多个实例示例</li>
                                        <li>设置合理的显示顺序，便于孩子循序渐进学习</li>
                                    </ul>
                                </div>
                            </div>
                            
                            <?php if ($isEditing): ?>
                            <div class="mt-4">
                                <a href="content_examples.php?content_id=<?php echo $content['content_id']; ?>&module_id=<?php echo $moduleId; ?>" class="btn btn-outline-info w-100">
                                    <i class="fas fa-images me-2"></i> 管理 "<?php echo htmlspecialchars($content['content_title']); ?>" 的示例
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="/admin/js/bootstrap.bundle.min.js"></script>
    <script src="/admin/js/jquery-3.6.0.min.js"></script>
    <script src="/admin/js/spectrum.min.js"></script>
    <script>
        $(document).ready(function() {
            // 颜色选择器
            $("#pick-color").spectrum({
                color: "<?php echo !empty($content['color_code']) ? $content['color_code'] : '#FF0000'; ?>",
                showInput: true,
                className: "full-spectrum",
                showInitial: true,
                showPalette: true,
                showSelectionPalette: true,
                maxSelectionSize: 10,
                preferredFormat: "hex",
                localStorageKey: "spectrum.kidsmind",
                palette: [
                    ["#FF0000", "#FF5E00", "#FFBB00", "#FFE400", "#ABF200", "#1DDB16", "#00D8FF", "#0054FF", "#0100FF", "#5F00FF", "#FF00DD", "#FF007F"],
                    ["#FFD6E0", "#D6E5FF", "#D6FFE1", "#FFEFD6", "#E9D6FF", "#FFAAA6", "#A6CAFF", "#A6FFB7", "#FFE2A6", "#D9A6FF"]
                ],
                show: function() {
                    
                },
                change: function(color) {
                    $("#color_code").val(color.toHexString());
                    $("#preview-color").css("background-color", color.toHexString());
                }
            });
            
            // 文件上传按钮显示所选文件名
            $('input[type="file"]').change(function(e) {
                var fileName = e.target.files[0].name;
                $(this).prev('button').text('已选择: ' + fileName);
            });
            
            // 移除音频复选框处理
            $('#remove_audio').change(function() {
                if ($(this).is(':checked')) {
                    $('input[name="title_audio"]').prop('disabled', true);
                    $('.audio-upload-wrapper button').addClass('disabled');
                } else {
                    $('input[name="title_audio"]').prop('disabled', false);
                    $('.audio-upload-wrapper button').removeClass('disabled');
                }
            });
            
            // 实时预览功能
            $('#content_title').on('input', function() {
                $('#preview-title').text($(this).val() || '内容标题');
            });
            
            $('#description').on('input', function() {
                $('#preview-description').html(($(this).val() || '内容描述将显示在这里...').replace(/\n/g, '<br>'));
            });
            
            $('#color_code').on('input', function() {
                $('#preview-color').css('background-color', $(this).val() || 'transparent');
            });
        });
    </script>
</body>
</html>

<?php
/**
 * 根据颜色名称获取颜色代码
 */
function getColorCode($colorName) {
    $colorMap = [
        'pink' => '#FFD6E0',
        'blue' => '#D6E5FF',
        'green' => '#D6FFE1',
        'yellow' => '#FFEFD6',
        'purple' => '#E9D6FF'
    ];
    
    return isset($colorMap[$colorName]) ? $colorMap[$colorName] : '#FFD6E0';
} 